public with sharing class Cald_ClaimExtensionVF {
    public Callidus_Claim__c claim {get; set;}
    private ID oppId = null;
    public List<Opportunity> opportunityList {get; set;}
    public Integer expectedCredit {get; set;}   
    public String claimedCredit {get; set;}   
    public String commissionRate {get; set;}    
    public String commissionAmount {get; set;} 
    public String comments {get; set;}  
    public Boolean approveButFlag {get; set;}
    public Boolean rejectButFlag {get; set;}
    public Boolean adjustAndApproveButFlag {get; set;}
    public Boolean sendInquiryButFlag {get; set;}
    public Boolean lookupPlanManagerButFlag {get; set;}
    public Boolean lookupPlanButFlag {get; set;}
    public Boolean claimedUserFlag {get; set;}
    public Boolean managerFlag {get; set;}
    public Boolean readOnlyFlag {get; set;}
    public Boolean editFlag {get; set;}
    public Boolean readOnlyOwnerFlag {get; set;}
    public Boolean lookUpButFlag {get; set;}
    public Boolean withdrawButFlag {get; set;}
    public Boolean fileClaimButFlag {get; set;}
    public Boolean addClaimantButFlag {get; set;}
    public Boolean estimateButFlag {get; set;}
    public Boolean fileDisputeButFlag {get; set;}
    public Boolean displayAssignedToFlag {get; set;}
    public Boolean displayDraftFlag {get; set;}
    public Boolean displayReadOnlyFlag {get; set;}
    public Boolean displayManagerEditFlag {get; set;}
    public Boolean displayCommentEditFlag {get; set;}
    public Boolean displayManagerFlag {get; set;}
    public Boolean displayManagerReadOnlyFlag {get; set;}
    public Boolean makeAdjustmentsFlag {get; set;}
    public Boolean cancelAdjustmentsFlag {get; set;}
    public Boolean isManagerFlag {get; set;}
    
    public List<Callidus_Claim_History__c> claimHistoriesList {get; set;}
    public List<ClaimHistories> claimHistoryList {get; set;}//WrapperClass
    public Callidus_Claim__c[] claimInstance {get; set;}
    public Callidus_Claim__c filingDateClaim {get; set;}
     
    
    public List<Callidus_Claim_Detail__c> cDetailsList {get; set;}
    public List<Callidus_Claim_Detail__c> dupCDetailsList {get; set;}
    
    private Map<ID, List<Callidus_Rate__c>> planRateMap = new Map<Id, List<Callidus_Rate__c>>(); 
    private Map<ID, Double> participantQuotaMap = new Map<Id, Double>(); 
    
    public List<Callidus_Claim_Detail__c> newClaimantsList {get; set;}
    public Map<ID, Callidus_Claim_Detail__c> claimantsMap {get; set;}
    public Callidus_Claim_Status_Credit__c[] existingCSCList {get; set;} 
    public Opportunity[] participantOppList {get; set;}
    
    public Integer selectedClaimantNumber {get; set;}
    public String ytdAttainment {get; set;}    
    public Callidus_Rate__c[] currentRateList {get; set;}     
    private Callidus_Plan_Assignable__c[] planAssignableList {get; set;}
    private Double sumOfOpenOpp = 0;
    private Double sumOfClosedOpp = 0;
    private Double sumOfPendingClaims = 0;
    private Double sumOfApprovedClaims = 0;
    private Double sumOfOpenOppsCommission = 0;
    private Double sumOfClosedOppsCommission = 0;
    private Double sumOfPendingClaimsCommission = 0;
    private Double sumOfApprovedClaimsCommission = 0;
    private Double cscAttainment = 0;
    private ID planId = null;
    private ID currentUsersPlanId = null;
    private Double planQuota = 0;
    private Double planOTE = 0;
    private String payoutType = '';
    public Double removeClaimDetailNum {get; set;}
    
    public Cald_ClaimExtensionVF(ApexPages.StandardController myController)
    {
        try
        {
            claim = (Callidus_Claim__c)myController.getRecord();
        		
        	cDetailsList = new List<Callidus_Claim_Detail__c>();
        	newClaimantsList = new List<Callidus_Claim_Detail__c>();
        	claimantsMap = new Map<ID, Callidus_Claim_Detail__c>();
        	commissionRate = '0';
        	selectedClaimantNumber = 0;
        	payoutType = '';
        		
            oppId = [select Opportunity__c from Callidus_Claim__c where id = : claim.id].Opportunity__c;
            opportunityList = [select Name, Amount, AccountId, Opportunity.Account.Name, ExpectedRevenue, Type, Description, OwnerId, Opportunity.Owner.Name, CloseDate, LeadSource, Opportunity.Campaign.Name, MainCompetitors__c, OrderNumber__c, CurrentGenerators__c, TrackingNumber__c from Opportunity where id = :oppId];
            ytdAttainment = String.valueOf(0.0);
  			 
			String status = getClaimHistories();
            claimInstance = [select id, Name, Opportunity__r.Amount, Commission_Amount__c, Claim_Status__c, Commission_Rate__c, Attainment__c, Credit__c, Comments__c, Adjusted_Credit__c, Adjusted_Commission__c, Assigned_To__c, Filing_Date__c, Level1_Approver__c, Level2_Approver__c, Level3_Approver__c, Level4_Approver__c, Level5_Approver__c, Level6_Approver__c, Final_Approver__c, OwnerId, Opportunity__c, (select Requested_Credit__c, Requested_Commission__c, Requested_Rate__c, Split__c, Claim__c, Claimant__c, Approved_Credit__c, Approved_Commission__c, Count__c, Plan__c, Payout_Type__c from Claim_Details__r) from Callidus_Claim__c where id = :claim.Id];
            isManagerFlag = displayCommentEditFlag = displayManagerFlag = displayManagerEditFlag = claimedUserFlag = makeAdjustmentsFlag = cancelAdjustmentsFlag = readOnlyFlag = editFlag = addClaimantButFlag = fileClaimButFlag = estimateButFlag = displayManagerReadOnlyFlag = displayDraftFlag = displayReadOnlyFlag = readOnlyOwnerFlag = readOnlyFlag = displayAssignedToFlag = fileDisputeButFlag = false;
            User[] isManagerUsersList = [select id from User where managerid = :UserInfo.getUserId() and IsActive = true];
            if(isManagerUsersList.size() > 0)
            {
            	isManagerFlag = true;
            }	 
            if(claimInstance.size() > 0 )
            {
	            oppId = claimInstance[0].Opportunity__c;
	            claim = claimInstance[0];
            	if(claimInstance[0].Claim_Status__c == 'Draft' && claimInstance[0].OwnerId == UserInfo.getUserId())
            	{
            		addCurrentUsersClaimDetailToList();
            	}
            	else if(claimInstance[0].Claim_Status__c == 'Pending Approval')
            	{
            		if(claimInstance[0].OwnerId == UserInfo.getUserId())
            			claimedUserFlag = withdrawButFlag = readOnlyFlag = true;
            		else
            			displayCommentEditFlag = makeAdjustmentsFlag = approveButFlag = rejectButFlag = displayManagerReadOnlyFlag = readOnlyFlag = true;
            			
           			populateClaimDetails(claimInstance[0].Claim_Details__r);
            			
            	}
            	else if(claimInstance[0].Claim_Status__c == 'Withdrawn')
            	{
           			readOnlyFlag = true;
           			
           			populateClaimDetails(claimInstance[0].Claim_Details__r);
            	}        	
            	else if(claimInstance[0].Claim_Status__c == 'Approved' || claimInstance[0].Claim_Status__c == 'Rejected')
            	{
            		if(claimInstance[0].OwnerId == UserInfo.getUserId())
            			fileDisputeButFlag = true;
           			displayManagerReadOnlyFlag = readOnlyFlag = true;
           			populateClaimDetails(claimInstance[0].Claim_Details__r);
            	}        	
            }
        }
        catch(Exception e)
        {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, e.getMessage()));
        }
        
    }
    
    private void addCurrentUsersClaimDetailToList()
    {
		claimedUserFlag = editFlag = fileClaimButFlag = addClaimantButFlag = estimateButFlag = true;
		Callidus_Claim_Detail__c cd = new Callidus_Claim_Detail__c(Claim__c = claim.id, Claimant__c = UserInfo.getUserId(), Split__c = 100, Requested_Credit__c = claimInstance[0].Credit__c, Approved_Credit__c = claimInstance[0].Credit__c, Count__c = 1);
        cd = getClaimObj(cd);
		cDetailsList.add(cd);
    } 
    
    public PageReference makeAdjustments()
    {
    	displayManagerReadOnlyFlag = makeAdjustmentsFlag = false;
    	displayCommentEditFlag = displayManagerEditFlag = cancelAdjustmentsFlag = true;
    	
    	return null;	
    }

    public PageReference cancelAdjustments()
    {
    	displayManagerReadOnlyFlag = makeAdjustmentsFlag = true;
    	displayCommentEditFlag = displayManagerEditFlag = cancelAdjustmentsFlag = false;
    	
    	return null;	
    }
    
    private List<Callidus_Claim_Detail__c> populateClaimDetails(List<Callidus_Claim_Detail__c> claimDetails)
    {
		for(Callidus_Claim_Detail__c ccd: claimDetails)
		{
			cDetailsList.add(ccd);
		}
		return cDetailsList;
    }
    
    private Callidus_Claim_Detail__c getClaimObj(Callidus_Claim_Detail__c ccd)
    {
        try
        {
            //Check if Plan is assigned to the Participant.
            planAssignableList = [select Id, Plan_Role__c, Plan__c, Quota__c, Plan__r.OTE__c from Callidus_Plan_Assignable__c p where p.Effective_Start_Date__c <= :opportunityList[0].CloseDate and p.Effective_End_Date__c >= :opportunityList[0].CloseDate and p.Participant__c = :ccd.Claimant__c order by createddate desc limit 1];
            Double ytdAtt = 0;
            planId = null;
            planQuota = planOTE = 0;
            payoutType = '';    
            try
            {
                if(planAssignableList.size() > 0)
                {
                    //Get the Plan and check if it Close Date falls in b/w Plan Period
                    planId = planAssignableList[0].Plan__c;
                    if(ccd.Claimant__c == UserInfo.getUserId())
                    	currentUsersPlanId = planId;
                    planQuota = planAssignableList[0].Quota__c;
                    planOTE = planAssignableList[0].Plan__r.OTE__c;
                }
/*                Callidus_Plan_Participant__c[] pList = [select YTD_Attainment__c from Callidus_Plan_Participant__c where Plan__c = :planId and Participant__c = :ccd.Claimant__c];
                
                for(Callidus_Plan_Participant__c p :pList)
                {
                    if(ytdAtt < p.YTD_Attainment__c)
                        ytdAtt = p.YTD_Attainment__c;
                } */
            }
            catch(Exception e)
            {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, e.getMessage()));
            }
            
            if(planAssignableList.size() > 0)
            {
            	ccd.Plan__c = planId;
            	
				Callidus_Claim_Detail__c[]  claimDetailsList = [select Approved_Credit__c from Callidus_Claim_Detail__c c where Claimant__c = :ccd.Claimant__c and c.Claim__r.Claim_Status__c = 'Approved' and Plan__c = :planId];                  
                Double approvedClaimedCredit = 0;
                Double totalCredit = 0;//sum of (approvedClaimedCredit + current approved amount)
                for(Callidus_Claim_Detail__c c: claimDetailsList)
                {
                    approvedClaimedCredit += c.Approved_Credit__c;   
                }
                currentRateList = new List<Callidus_Rate__c>();
                
                currentRateList = [select Rate_Type__c, Min_Attainment__c, Max_Attainment__c, Min_Credit__c, Max_Credit__c, Rate__c from Callidus_Rate__c where Plan__c = :planId];
                planRateMap.put(planId, currentRateList);
                participantQuotaMap.put(ccd.Claimant__c, planQuota);
                
                if(currentRateList.size() > 0)
                {
                    payoutType = currentRateList[0].Rate_Type__c;
                    ccd.Payout_Type__c = currentRateList[0].Rate_Type__c;
                }

                totalCredit = approvedClaimedCredit + ccd.Approved_Credit__c;
                    
                if(currentRateList[0].Rate_Type__c == 'Attainment')
                {
                        ytdAttainment = String.valueOf(ytdAtt);
                        Double cRate = (totalCredit * 100)/planQuota;
                        
                        for(Callidus_Rate__c r: currentRateList)
                        {
                            if(cRate >= r.Min_Attainment__c && cRate <= r.Max_Attainment__c)
                            {
                                ccd.Requested_Rate__c = r.Rate__c;
                                break;
                            }
                        }
                }//end ofif(currentRateList[0].Rate_Type__c == 'Attainment')
                else
                {
                    ytdAttainment = String.valueOf(approvedClaimedCredit);
                    for(Callidus_Rate__c r: currentRateList)
                    {
                        if(totalCredit >= r.Min_Credit__c && totalCredit <= r.Max_Credit__c)
                        {
                            ccd.Requested_Rate__c = r.Rate__c;
                            break;
                        }
                    }
                }
               
           		ccd.Requested_Commission__c = (ccd.Requested_Rate__c * ccd.Requested_Credit__c) / 100;
                ccd.Approved_Commission__c = ccd.Requested_Commission__c;
            }//end of if(planAssignableList.size() > 0)
            else
            {
                payoutType = 'Credit';
                ccd.Payout_Type__c = currentRateList[0].Rate_Type__c;
                ccd.Requested_Commission__c = 0;
                ccd.Approved_Commission__c = 0;
                ytdAttainment = String.valueOf(0);
            }
        }
        catch(Exception e)
        {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, e.getMessage()));
        }
        
        return ccd;
    }//end of getClaimObj()
    
    public PageReference estimate()
    {
    	if(!isSplitEqualToHundred())
    	{
    		return null;
    	}
		Double splitTot = 0; 
		Double hundred = 100;
    	for(Callidus_Claim_Detail__c c: cDetailsList)
    	{
    		if(c.Claimant__c != null)
			{
		   		splitTot += c.Split__c;
		   		if(splitTot > hundred)
					ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, 'Split % should be equal to 100.'));
				
				c.Requested_Credit__c = (claim.Credit__c * c.split__c)/100;
				//c.Requested_Rate__c = Double.valueOf(commissionRate);
				c.Requested_Commission__c = (c.Requested_Credit__c * Double.valueOf(c.Requested_Rate__c)) / 100;
			}	   		 
    	}
    	
    	return null;	
    }
    
    public PageReference deriveRate()
    {
        try
        {
	    	for(Callidus_Claim_Detail__c c: cDetailsList)
	    	{
	    		if(c.Count__c == selectedClaimantNumber)
				{
					if(c.Claimant__c == null)
					{
						ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, 'Please select claimant.'));
						return null;
					}
					if(c.Split__c == null)
					{
						ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, 'Please enter the Split% value.'));
						return null;
					}
					if(c.Requested_Commission__c != null && c.Requested_Commission__c != 0)
					{
						c.Requested_Rate__c = (c.Requested_Commission__c * 100)/c.Requested_Credit__c;
						break;
					}
				}	   		 
	    	}
        	
        }
        catch(Exception e)
        {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, e.getMessage()));
        }
        return null;
    }    

    public PageReference deriveClaimantDetails()
    {
    	
        try
        {
	    	for(Callidus_Claim_Detail__c c: cDetailsList)
	    	{
	    		if(c.Count__c == selectedClaimantNumber)
				{
					if(c.Claimant__c == null)
					{
						ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, 'Please select claimant.'));
						return null;
					}
					if(c.Split__c != null)
					{
						c.Approved_Credit__c = c.Requested_Credit__c = (claim.Credit__c * c.split__c)/100;
						getClaimObj(c);
						break;
					}
				}	   		 
	    	}
      /*  	if(!isSplitEqualToHundred())
        	{
        		return null;
        	}
        */	
        }
        catch(Exception e)
        {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, e.getMessage()));
        }
        return null;
    }    
    
    public PageReference removeClaimDetail()
    {
    	Integer claimantsCount = 1;
    	try
    	{
			cDetailsList.remove(removeClaimDetailNum.intValue() - 1);
	    	for(Callidus_Claim_Detail__c cd: cDetailsList)
	    		cd.Count__c = claimantsCount++;
    	}
    	catch(Exception e)
    	{
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, e.getMessage()));
    	}
    	return null;
    }

    public PageReference addClaimants()
    {
    	Integer claimantsCount = 1;
    	cDetailsList.add(new Callidus_Claim_Detail__c(Claim__c = claim.id));
    	
    	for(Callidus_Claim_Detail__c cd: cDetailsList)
    		cd.Count__c = claimantsCount++;
    	return null;
    }

    private Boolean areAllClaimantsSelected()
    {
    	for(Callidus_Claim_Detail__c c: cDetailsList)
    	{
    		if(c.Claimant__c == null)
			{
				ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, 'Please select claimant for each row.'));
				return false;
			}	   		 
    	}
    	return true;	
    }

    private Boolean areAllCommissionsPopulated()
    {
    	for(Callidus_Claim_Detail__c c: cDetailsList)
    	{
    		if(c.Requested_Commission__c == null || c.Requested_Commission__c == 0)
			{
				ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, 'Please enter Requested Commission.'));
				return false;
			}	   		 
    	}
    	return true;	
    }
    
    private Boolean isSplitEqualToHundred()
    {
		Double splitTot = 0; 
		Double hundred = 100;
		Double zero = 0;
    	
    	for(Callidus_Claim_Detail__c c: cDetailsList)
    	{
    		if(c.Claimant__c != null && c.Split__c != null)
			{
		   		splitTot += c.Split__c;
		   		if(splitTot > hundred)
		   		{
					ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, 'Split % should be equal to 100.'));
					return false;
		   		}
			}	   		 
    	}
   		if(splitTot < hundred)
   		{
			ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, 'Split % should be equal to 100.'));
			return false;
   		}

    	return true;
    }
    
    public List<Opportunity> getOpportunityDetails()
    {
        opportunityList = [select Name, Amount, AccountId, Opportunity.Account.Name, ExpectedRevenue, Type, Description, OwnerId, Opportunity.Owner.Name, CloseDate, LeadSource, Opportunity.Campaign.Name, MainCompetitors__c, OrderNumber__c, CurrentGenerators__c, TrackingNumber__c from Opportunity where id = :oppId];
        filingDateClaim = new Callidus_Claim__c(Filing_Date__c = opportunityList[0].CloseDate);
        return opportunityList;
    }
    
    public PageReference withdraw()
    {
    	PageReference p = null;
    	try
    	{
	        ProcessInstance[] prInst = [Select Id from ProcessInstance where TargetObjectId=:claim.Id and Status='Pending'];
	        if(prInst.size()>0)     
	        {
	    	
	            ProcessInstanceWorkitem[] prInstWItem = [select Id,OriginalActorId from ProcessInstanceWorkitem where ProcessInstanceId = :prInst[0].Id]; 
	    
	            Approval.ProcessWorkitemRequest prWkItem = new Approval.ProcessWorkitemRequest();
	    
	            prWkItem.setWorkitemId(prInstWItem[0].Id);
	    
	            prWkItem.setComments('Withdrawn'); 
	                
	            prWkItem.setAction('Removed'); 
	
	            Approval.ProcessResult prResult = Approval.process(prWkItem);
	        }
	    	
	        claim.Claim_Status__c = 'Withdrawn';
            claim.Assigned_To__c = null;
	        update claim;
	        
	        Callidus_Claim__c newClaim = null;
	        if(currentUsersPlanId != null)
	        	newClaim = new Callidus_Claim__c(Opportunity__c = oppId, Plan__c = currentUsersPlanId, Claim_Status__c = 'Draft', Credit__c = opportunityList[0].Amount);
	        else
	        	newClaim = new Callidus_Claim__c(Opportunity__c = oppId, Claim_Status__c = 'Draft', Credit__c = opportunityList[0].Amount);
	        	
			insert newClaim;	        
			p = new PageReference('/apex/CCM__Cald_Claim_Detail?id='+newClaim.Id);
			p.setRedirect(true);
    	}
    	catch(Exception e)
    	{
    		if(e.getMessage().indexOf('ENTITY_IS_LOCKED') != -1 || e.getMessage().indexOf('INSUFFICIENT_ACCESS_ON_CROSS_REFERENCE_ENTITY') != -1)
    			ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, 'Request your System Admin to enable <b>Recal Approval Requests</b>'));
    		else
    			ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, e.getMessage()));
    	}

        return p;
    }

    public PageReference lookupPlanDocument()
    {
        return null;
    }
    
    

    public PageReference fileClaim()
    {
    
        try
        {
        	if(cDetailsList.size() == 0)
				ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, 'There are no claimants added.'));
			
			if(!areAllClaimantsSelected())
				return null;
					        	
        	if(!isSplitEqualToHundred())
        		return null;
        	
        	if(!areAllCommissionsPopulated())
        		return null;
        	
            List<User> managerList = [select ManagerId from User where id = :UserInfo.getUserId()];
            ID managerId = null;
 			if(managerList.size() > 0 && managerList[0].managerId != null)
            {
                managerId = managerList[0].managerId;
                displayAssignedToFlag = true;
            }
            
			if(currentUsersPlanId != null)
            	claim.Plan__c = currentUsersPlanId;
            	
          	claim.Participant__c = UserInfo.getUserId();
          	claim.Payout_Type__c = payoutType;
          	claim.Adjusted_Credit__c = 0;
          	claim.Adjusted_Commission__c = 0;
          	claim.Commission_Amount__c = 0;
          	
          	for(Callidus_Claim_Detail__c ccd : cDetailsList)
          	{
          		ccd.Approved_Credit__c = ccd.Requested_Credit__c;
	          	claim.Adjusted_Credit__c += ccd.Approved_Credit__c;
	          	
	          	claim.Commission_Amount__c += ccd.Requested_Commission__c;
	          	
	          	ccd.Approved_Commission__c = ccd.Requested_Commission__c;
	          	claim.Adjusted_Commission__c +=  ccd.Approved_Commission__c;
          	}
          	claim.Commission_Rate__c =  (claim.Adjusted_Commission__c * 100) / claim.Adjusted_Credit__c ;
          	
            claim.Opportunity__c = oppId;
          	claim.Claim_Status__c = 'Pending Approval';
			if(managerId != null)
          		claim.Assigned_To__c = managerId;
          		
          	if(cDetailsList.size() > 1)
          		claim.Is_Multiple_Claimants__c = 'yes';
          		
            Callidus_Configuration__c[] configList = [select IsFinalApprover__c, Response_Window__c, Approver__c, Approver_Level__c from Callidus_Configuration__c where Is_Dispute__c = false];
            if(configList.size() > 0)
            {
                User[] user = [Select Id, managerId from User us where us.Id = :UserInfo.getUserId()];
                Double d = 0;
                for(Callidus_Configuration__c c: configList)
                {
                    d = c.Response_Window__c;
                    if(c.IsFinalApprover__c == 'No' && user.size() > 0 && user[0].managerId != null)
                    {
                        if(claim.Level1_Approver__c == null)
                        {
                            claim.Level1_Approver__c = user[0].managerId;
                            claim.Level1_Approver_DueDate__c = Date.today() + d.round();
                        }
                        else if(claim.Level2_Approver__c == null)
                        {
                            claim.Level2_Approver__c = user[0].managerId;
                            claim.Level2_Approver_DueDate__c = Date.today() + d.round();
                        }
                        else if(claim.Level3_Approver__c == null)
                        {
                            claim.Level3_Approver__c = user[0].managerId;
                            claim.Level3_Approver_DueDate__c = Date.today() + d.round();
                        }
                        else if(claim.Level4_Approver__c == null)
                        {
                            claim.Level4_Approver__c = user[0].managerId;
                            claim.Level4_Approver_DueDate__c = Date.today() + d.round();
                        }
                        else if(claim.Level5_Approver__c == null)
                        {
                            claim.Level5_Approver__c = user[0].managerId;
                            claim.Level5_Approver_DueDate__c = Date.today() + d.round();
                        }
                        else if(claim.Level6_Approver__c == null)
                        {
                            claim.Level6_Approver__c = user[0].managerId;
                            claim.Level6_Approver_DueDate__c = Date.today() + d.round();
                        }
                        user = [Select Id, managerId from User us where us.Id= :user[0].managerId];
                    }
                    if(c.Approver_Level__c != 'select' && c.IsFinalApprover__c == 'Yes' && user.size() > 0 && user[0].managerId != null)
                    {
                        if(claim.Final_Approver__c == null)
                        {
                            claim.Final_Approver__c = c.Approver_Level__c;
                            claim.Final_Approver_DueDate__c = Date.today() + d.round();
                        }
                    }
                }
            }
            else
            {
                ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, 'Approvers are not Configured'));
                return null;
            }
            
            update claim;
            
			insert cDetailsList;

            addToAuditAndHistory('Filed');

            //Do all DML operations above this, else it will fail
            Approval.ProcessSubmitRequest request = new Approval.ProcessSubmitRequest();
            request.setObjectId(claim.Id);
            Approval.ProcessResult result = Approval.process(request);
                  
            claimedUserFlag = editFlag = fileClaimButFlag = estimateButFlag = addClaimantButFlag = false;
            readOnlyFlag = withdrawButFlag = true;
            
            String st = getClaimHistories();
            
            String currentYear = String.valueOf(opportunityList[0].CloseDate.year());
            Date startDate = Date.valueOf(currentYear+'-01-01 00:00:00');           
            Date endDate = Date.valueOf(currentYear+'-12-31 23:59:00');
            String[] claimStatusArray = new String[]{'Pending Approval', 'Approved'};           

            Callidus_Claim__Share[] csList = new Callidus_Claim__Share[]{}; 
      
	    	for(Callidus_Claim_Detail__c ccDetail: cDetailsList)
	    	{
	    		sumOfApprovedClaims = sumOfApprovedClaimsCommission = sumOfClosedOpp = sumOfClosedOppsCommission = sumOfOpenOpp = sumOfOpenOppsCommission = sumOfPendingClaims = sumOfPendingClaimsCommission = 0;
	    		planQuota = participantQuotaMap.get(ccDetail.Claimant__c);
	    		
	            existingCSCList = [select id, Attainment__c, Participant__c, Amount__c, Commission__c, FYear__c, Claim_Status__c from Callidus_Claim_Status_Credit__c where Participant__c = :ccDetail.Claimant__c and FYear__c = :opportunityList[0].CloseDate.Year() and Claim_Status__c != 'Approved Claims'];
	       
	            //Add ownerid to the where clause to get only the Current Users Opportunity. 
	            participantOppList = [select id, StageName, Amount from Opportunity where OwnerId = :ccDetail.Claimant__c and Opportunity.FiscalYear = :opportunityList[0].CloseDate.year() limit 1000];
	            for(Opportunity o : participantOppList)
	            {
	                if(o.StageName == 'Closed Won')
	                    sumOfClosedOpp += o.Amount;
	                else
	                    sumOfOpenOpp += o.Amount;
	            }
			            
	            Callidus_Claim_Detail__c[] pendingApprovedClaimList = [select Approved_Credit__c, Approved_Commission__c, Claim__r.Claim_Status__c from Callidus_Claim_Detail__c c where c.Claimant__c = :ccDetail.Claimant__c and c.Claim__r.Filing_Date__c >= :startDate and c.Claim__r.Filing_Date__c <= :endDate and c.Claim__r.Claim_Status__c in :claimStatusArray];
	      
	            for(Callidus_Claim_Detail__c c: pendingApprovedClaimList)
	            {
	                if(c.Claim__r.Claim_Status__c == 'Pending Approval')
	                {
		                sumOfPendingClaims += c.Approved_Credit__c;
		                sumOfPendingClaimsCommission += c.Approved_Commission__c;
	                }
	                else
	                {
	                    sumOfApprovedClaims += c.Approved_Credit__c;
	                    sumOfApprovedClaimsCommission += c.Approved_Commission__c;
	                }
	            }
	            
	            
	            if(existingCSCList != null && existingCSCList.size() > 0)
	            {
	                for(Callidus_Claim_Status_Credit__c csc : existingCSCList)
	                {
	                    if(csc.Claim_Status__c == 'All Open Opportunities')
	                    {
			                csc.Amount__c = sumOfOpenOpp;
	                        csc.Commission__c = (getCommissionRate(sumOfOpenOpp, ccDetail.Plan__c) * sumOfOpenOpp)/100;
	                    }
	                    else if(csc.Claim_Status__c == 'Closed Won Opportunities')
	                    {
	                    	Double val = 0;
	                		val = (sumOfClosedOpp - (sumOfPendingClaims + sumOfApprovedClaims));
	                        csc.Amount__c = val;
	                        csc.Commission__c = (getCommissionRate(val, ccDetail.Plan__c) * val)/100;
	                    }
	                    else if(csc.Claim_Status__c == 'Pending Claims')
	                    {
	                        csc.Amount__c = sumOfPendingClaims;// + ccDetail.Approved_Credit__c;
	                        csc.Commission__c = sumOfPendingClaimsCommission;// + ccDetail.Approved_Commission__c;
	                    }
	                    if(planQuota != null && planQuota > 0)
	                    	csc.Attainment__c = (csc.Amount__c.doubleValue() * 100) /planQuota;
	                }
	                
	                update existingCSCList;
	            }
	            else
	            {
	                List<Callidus_Claim_Status_Credit__c> newCSCList = new List<Callidus_Claim_Status_Credit__c>();
	                Callidus_Claim_Status_Credit__c newObj = new Callidus_Claim_Status_Credit__c(Participant__c = ccDetail.Claimant__c, FYear__c = opportunityList[0].CloseDate.year(), Claim_Status__c = 'All Open Opportunities', Amount__c = sumOfOpenOpp, Commission__c = ((getCommissionRate(sumOfOpenOpp, ccDetail.Plan__c) * sumOfOpenOpp)/100), Attainment__c = ((planQuota != null && planQuota > 0) ? ((sumOfOpenOpp * 100) /planQuota) : 0), OwnerId = ccDetail.Claimant__c, Claim_Status_Order__c = '1 - All Open Opportunities');
	                newCSCList.add(newObj);
	
	                Double tempVal = 0;
	                tempVal = (sumOfClosedOpp - (sumOfPendingClaims + ccDetail.Approved_Credit__c + sumOfApprovedClaims));
	                newObj =  new Callidus_Claim_Status_Credit__c(Participant__c = ccDetail.Claimant__c, FYear__c = opportunityList[0].CloseDate.year(), Claim_Status__c = 'Closed Won Opportunities', Amount__c = (sumOfClosedOpp - ccDetail.Approved_Credit__c), Commission__c = ((getCommissionRate(tempVal, ccDetail.Plan__c) * tempVal)/100), Attainment__c = ((planQuota != null && planQuota > 0)?((tempVal * 100) /planQuota) : 0), OwnerId = ccDetail.Claimant__c, Claim_Status_Order__c = '2 - Closed Won Opportunities');
	                newCSCList.add(newObj);

	                tempVal = (sumOfPendingClaims); //+ ccDetail.Approved_Credit__c);
	                newObj =  new Callidus_Claim_Status_Credit__c(Participant__c = ccDetail.Claimant__c, FYear__c = opportunityList[0].CloseDate.year(), Claim_Status__c = 'Pending Claims', Amount__c = tempVal, Commission__c = ((getCommissionRate(tempVal, ccDetail.Plan__c) * tempVal)/100), Attainment__c = ((planQuota != null && planQuota > 0) ? ((tempVal * 100) /planQuota) : ccDetail.Approved_Credit__c), OwnerId = ccDetail.Claimant__c, Claim_Status_Order__c = '3 - Pending Claims');
	                newCSCList.add(newObj);
			        
	                newObj =  new Callidus_Claim_Status_Credit__c(Participant__c = ccDetail.Claimant__c, FYear__c = opportunityList[0].CloseDate.year(), Claim_Status__c = 'Approved Claims', Amount__c = 0, Commission__c = 0, OwnerId = ccDetail.Claimant__c, Claim_Status_Order__c = '4 - Approved Claims');
	                newCSCList.add(newObj);

	                insert newCSCList;
	            }
	            
	            Schema.Describesobjectresult claimSObj = Callidus_Claim__c.sObjectType.getDescribe();
	            if(ccDetail.Claimant__c != UserInfo.getUserId() && !claimSObj.isDeletable())
				{
					Callidus_Claim__Share cShare  = new Callidus_Claim__Share();
					cShare.ParentId = claim.Id;
					// Set the ID of user or group being granted access.
					cShare.UserOrGroupId = ccDetail.Claimant__c;
					// Set the access level.
					cShare.AccessLevel = 'edit';
					cShare.RowCause = Schema.Callidus_Claim__Share.RowCause.Manual;
					csList.add(cShare);
				}
			
	    	}//end of for loop   
	    	if(csList.size() > 0)
				Database.SaveResult[] sr = Database.insert(csList,false);
	    		         
        }
        catch(Exception e)
        {
        	if(e.getMessage().indexOf('MANAGER_NOT_DEFINED') != -1)
        		ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, 'Manager is not defined for the User.'));
        	else
            	ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, e.getMessage()));
        }        
        return null;
    }

    private Double getCommissionRate(Double creditAmount, ID pId)
    {
    	if(pId != null)
    	{
    		currentRateList = planRateMap.get(pId);
	        if(currentRateList[0].Rate_Type__c == 'Attainment')
	        {
	                Double cRate = (creditAmount * 100) / planQuota;
	                
	                for(Callidus_Rate__c r: currentRateList)
	                {
	                    if(cRate >= r.Min_Attainment__c && cRate <= r.Max_Attainment__c)
	                        return r.Rate__c;
	                }
	        }//end ofif(currentRateList[0].Rate_Type__c == 'Attainment')
	        else
	        {
	            for(Callidus_Rate__c r: currentRateList)
	            {
	                if(creditAmount >= r.Min_Credit__c && creditAmount <= r.Max_Credit__c)
	                    return r.Rate__c;
	            }
	        }
    	}
        return 0;
    }     
    
    
    private void addToAuditAndHistory(String cStatus)
    {
        Callidus_Claim_Audit__c ca = new Callidus_Claim_Audit__c(Claim__c = claim.id, claim_status__c = cStatus, Submission_Date__c = Date.today(), Comments__c = claim.Comments__c);
        insert ca;
        Callidus_Claim_History__c ch = new Callidus_Claim_History__c(Claim__c = claim.id, Comments__c = claim.Comments__c, Action_Date__c = Date.today(), Claim_Status__c = cStatus, User__c = UserInfo.getUserId());
        insert ch;
    }
    
    public PageReference approve()
    {
        try
        {
            List<User> managerList = [select ManagerId from User where id = :UserInfo.getUserId()];
            
            if(claim.Level1_Approver__c == claim.Assigned_To__c && claim.Level2_Approver__c != null && managerList.size() > 0 && managerList[0].managerId != null)
            {
                claim.Assigned_To__c = managerList[0].managerId;
                displayAssignedToFlag = true;
            }
            else if(claim.Level2_Approver__c == claim.Assigned_To__c && claim.Level3_Approver__c != null && managerList.size() > 0 && managerList[0].managerId != null)
            {
                claim.Assigned_To__c = managerList[0].managerId;
                displayAssignedToFlag = true;
            }
            else if(claim.Level3_Approver__c == claim.Assigned_To__c && claim.Level4_Approver__c != null && managerList.size() > 0 && managerList[0].managerId != null)
            {
                claim.Assigned_To__c = managerList[0].managerId;
                displayAssignedToFlag = true;
            }
            else if(claim.Level4_Approver__c == claim.Assigned_To__c && claim.Level5_Approver__c != null && managerList.size() > 0 && managerList[0].managerId != null)
            {
                claim.Assigned_To__c = managerList[0].managerId;
                displayAssignedToFlag = true;
            }
            else if(claim.Level5_Approver__c == claim.Assigned_To__c && claim.Level6_Approver__c != null && managerList.size() > 0 && managerList[0].managerId != null)
            {
                claim.Assigned_To__c = managerList[0].managerId;
                displayAssignedToFlag = true;
            }
            else if(claim.Level6_Approver__c == claim.Assigned_To__c && claim.Level7_Approver__c != null && managerList.size() > 0 && managerList[0].managerId != null)
            {
                claim.Assigned_To__c = managerList[0].managerId;
                displayAssignedToFlag = true;
            }
            else if(claim.Final_Approver__c != null)
            {
                claim.Assigned_To__c = claim.Final_Approver__c;
                displayAssignedToFlag = true;
            }
            else
                claim.Assigned_To__c = null;
                
            update cDetailsList;
            
    		claim.Adjusted_Commission__c = 0 ; 
    		claim.Adjusted_Credit__c = 0;
            for(Callidus_Claim_Detail__c c: cDetailsList)
	    	{
	    		claim.Adjusted_Commission__c += c.Approved_Commission__c;
	    		claim.Adjusted_Credit__c += c.Approved_Credit__c;
	    	}
            
            update claim;
            
            ProcessInstance[] prInst = [Select Id from ProcessInstance where TargetObjectId=:claim.Id and Status='Pending'];
            if(prInst.size()>0)     
            {
                Callidus_Claim_Audit__c ca = new Callidus_Claim_Audit__c(Claim__c = claim.id, claim_status__c = 'Approved', Approver__c = UserInfo.getUserId(), Approved_Date__c = Date.today(), Comments__c = comments);
                insert ca;

                Callidus_Claim_History__c ch = new Callidus_Claim_History__c(Claim__c = claim.id, Comments__c = comments, Action_Date__c = Date.today(), Claim_Status__c = (makeAdjustmentsFlag == false ? 'Adjusted and Approved' :'Approved'), User__c = UserInfo.getUserId());
                insert ch;
                String status = getClaimHistories();
    
                ProcessInstanceWorkitem[] prInstWItem = [select Id,OriginalActorId from ProcessInstanceWorkitem where ProcessInstanceId = :prInst[0].Id]; 
    
                Approval.ProcessWorkitemRequest prWkItem = new Approval.ProcessWorkitemRequest();
    
                prWkItem.setWorkitemId(prInstWItem[0].Id);
    
                prWkItem.setComments(comments); 
                
                prWkItem.setAction('Approve'); 

                Approval.ProcessResult prResult = Approval.process(prWkItem);
                
                //Hide the Approve and reject buttons
                approveButFlag = rejectButFlag = !approveButFlag;
                displayManagerReadOnlyFlag = readOnlyFlag = true;
                displayCommentEditFlag = makeAdjustmentsFlag = cancelAdjustmentsFlag = displayManagerEditFlag = displayManagerFlag = managerFlag = false;
                claim = getClaim();
            }
        }
        catch(Exception e)
        {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, e.getMessage()));
        }
        return null;
    }

    public PageReference reject()
    {
        try
        {
            claim.Comments__c = comments;
          //  claim.Claim_Status__c = 'Approved';
            //claim.Commission_Rate__c = Double.valueOf(commissionRate);
            update cDetailsList;
            
    		claim.Adjusted_Commission__c = 0 ; 
    		claim.Adjusted_Credit__c = 0;
            for(Callidus_Claim_Detail__c c: cDetailsList)
	    	{
	    		claim.Adjusted_Commission__c += c.Approved_Commission__c;
	    		claim.Adjusted_Credit__c += c.Approved_Credit__c;
	    	}
            
            update claim;
            ProcessInstance[] prInst = [Select Id from ProcessInstance where TargetObjectId=:claim.Id and Status='Pending'];
            if(prInst.size()>0)     
            {
                Callidus_Claim_Audit__c ca = new Callidus_Claim_Audit__c(Claim__c = claim.id, claim_status__c = 'Rejected', Approver__c = UserInfo.getUserId(), Approved_Date__c = Date.today(), Comments__c = comments);
                insert ca;

                Callidus_Claim_History__c ch = new Callidus_Claim_History__c(Claim__c = claim.id, Comments__c = comments, Action_Date__c = Date.today(), Claim_Status__c = 'Rejected', User__c = UserInfo.getUserId());
                insert ch;
                String status = getClaimHistories();
    
                ProcessInstanceWorkitem[] prInstWItem = [select Id, OriginalActorId from ProcessInstanceWorkitem where ProcessInstanceId = :prInst[0].Id]; 
    
                Approval.ProcessWorkitemRequest prWkItem = new Approval.ProcessWorkitemRequest();
    
                prWkItem.setWorkitemId(prInstWItem[0].Id);
    
                prWkItem.setComments(comments); 
                
                prWkItem.setAction('Reject'); 

                Approval.ProcessResult prResult = Approval.process(prWkItem);
                
                //Hide the Approve and reject buttons
                approveButFlag = rejectButFlag = !approveButFlag;
                displayManagerReadOnlyFlag = readOnlyFlag = true;
                displayCommentEditFlag = makeAdjustmentsFlag = cancelAdjustmentsFlag = displayManagerEditFlag = displayManagerFlag = managerFlag = false;
                claim = getClaim();
            }
        }
        catch(Exception e)
        {
            ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, e.getMessage()));
        }
        return null;
    }
    
    public PageReference fileDispute()
    {
    	PageReference p = null;
    	Callidus_Dispute__c cd = new Callidus_Dispute__c(Status__c = 'Draft', Claim__c = claim.id);
    	insert cd;
        p = new PageReference('/apex/Cald_NewDispute?id='+cd.id);
        p.setRedirect(true);
    	return p;
    }
    
    public Callidus_Claim__c getClaim()
    {
        Callidus_Claim__c[] claimObj =  [select id, Name, Opportunity__r.Amount, Commission_Amount__c, Claim_Status__c, Commission_Rate__c, Attainment__c, Credit__c, Comments__c, Adjusted_Credit__c, Adjusted_Commission__c, Assigned_To__c, Filing_Date__c, Level1_Approver__c, Level2_Approver__c, Level3_Approver__c, Level4_Approver__c, Level5_Approver__c, Level6_Approver__c, Final_Approver__c, OwnerId, Opportunity__c, (select Requested_Credit__c, Requested_Commission__c, Requested_Rate__c, Split__c, Claim__c, Claimant__c, Approved_Credit__c, Approved_Commission__c, Count__c, Plan__c, Payout_Type__c from Claim_Details__r) from Callidus_Claim__c where id = :claim.Id];
        //ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, ''+claim));
        if(claimObj.size() > 0)
        {
            commissionRate = String.valueOf(claimObj[0].Commission_Rate__c);
        }
        
        return claimObj[0];
    }

    public Callidus_Claim__c getClaimData()
    {
        return claim;
    }

    private String getClaimHistories()
    {
        claimHistoriesList = [select Comments__c, Claim_Status__c, User__c, User__r.Name, Action_Date__c from Callidus_Claim_History__c where Claim__c = :claim.id order by createddate desc];
        if(claimHistoriesList.size() > 0)
            claimHistoryList = new List<ClaimHistories>();
        else 
            claimHistoryList = null;
            
        for(Callidus_Claim_History__c ch : claimHistoriesList)
        {
            claimHistoryList.add(new ClaimHistories(ch.Comments__c, ch.Claim_Status__c, ch.User__r.Name, ch.User__c, ch.Action_Date__c));
        }

        return 'success';
        //ApexPages.addMessage(new ApexPages.Message(ApexPages.severity.info, String.valueOf(claimHistoriesList.size())+'  -----------------  '+claimHistoriesList));
    }//end of getClaimHistories()
    
    public class ClaimHistories
    {
        public String Comments {get; set;}
        public String claimStatus {get; set;}
        public String userName {get; set;}
        public ID userId {get; set;}
        public String actionDate {get; set;}
        public ClaimHistories(String com, String status, String uName, Id uId, Date d)
        {
            Comments = com; 
            claimStatus = status;
            userName = uName;
            userId = uId;
            actionDate = d.Month()+'/'+d.Day()+'/'+d.Year();
        }
    }
    
    public List<ClaimHistories> getClaimHistorys() {
        return claimHistoryList;
    }
    
    public String changeCC()
    {
        return 'success';      
    }
    

    static testMethod void testCald_ClaimExtensionVF()
    {
        PageReference pg = Page.Cald_Claim_Detail;
        Test.setCurrentPage(pg);
        
        Opportunity o = [select Id, Name, Amount, AccountId, Opportunity.Account.Name, ExpectedRevenue, Type, Description, OwnerId, Opportunity.Owner.Name, CloseDate, LeadSource, Opportunity.Campaign.Name, MainCompetitors__c, OrderNumber__c, CurrentGenerators__c, TrackingNumber__c from Opportunity where StageName = 'Closed Won' limit 1];
		Test.startTest();
        Callidus_Plan__c plan = new Callidus_Plan__c(Name = 'Test', Start_Date__c = (Date.today() - 1000), End_Date__c = (Date.today() + 100), Quota__c = 1000000, Type__c = 'byRole');
        insert plan;
		List<Callidus_Plan__c> tPlan = [select Name from Callidus_Plan__c where id = :plan.id];
		for(Callidus_Plan__c p:tPlan)
		{
			System.assertEquals('Test', p.Name);
		}
        
        Callidus_Rate__c rate = new Callidus_Rate__c(Plan__c = plan.id, Min_Attainment__c = 0, Max_attainment__c = 100, Rate__c = 1, Rate_Type__c = 'Attainment');
        insert rate;
		List<Callidus_Rate__c> tRate = [select Rate_Type__c from Callidus_Rate__c where Plan__c = :plan.id];
		for(Callidus_Rate__c p:tRate)
		{
			System.assertEquals('Attainment', p.Rate_Type__c);
		}
        rate = new Callidus_Rate__c(Plan__c = plan.id, Min_Attainment__c = 100, Max_attainment__c = 110, Rate__c = 2, Rate_Type__c = 'Attainment');
        insert rate;
		tRate = [select Rate_Type__c from Callidus_Rate__c where Plan__c = :plan.id];
		for(Callidus_Rate__c p:tRate)
		{
			System.assertEquals('Attainment', p.Rate_Type__c);
		}
        
        Callidus_Claim__c c = new Callidus_Claim__c(Opportunity__c = o.id, Claim_Status__c = 'Approved', Filing_Date__c = Date.today(), Participant__c = UserInfo.getUserId(), Plan__c = plan.id);
        insert c;
		List<Callidus_Claim__c> tClaim = [select Claim_Status__c from Callidus_Claim__c where Plan__c = :plan.id];
		for(Callidus_Claim__c p:tClaim)
		{
			System.assertEquals('Approved', p.Claim_Status__c);
		}

        ApexPages.StandardController mc = new Apexpages.Standardcontroller(c);
        Cald_ClaimExtensionVF ce = new Cald_ClaimExtensionVF(mc);
        
        system.assertEquals(ce.claim, ce.getClaimData());
        system.assertEquals(ce.claim, ce.getClaim());
        system.assertEquals(null, ce.deriveRate());
        
        system.assertEquals(ce.claimHistoryList, ce.getClaimHistorys());
        
        system.assertNotEquals('Test', ce.getOpportunityDetails().get(0).Name);
        system.assertEquals(null, ce.lookupPlanDocument());
        system.assertEquals(null, ce.fileClaim());
		
		ce.addClaimants();
		ce.addCurrentUsersClaimDetailToList();
		ce.addToAuditAndHistory('Filed');
		ce.areAllClaimantsSelected();
		ce.areAllCommissionsPopulated();
		ce.cancelAdjustments();
		ce.makeAdjustments();
		ce.deriveClaimantDetails();
		
        Callidus_Claim_Audit__c ca = new Callidus_Claim_Audit__c(Claim__c = c.id, claim_status__c = 'Filed', Submission_Date__c = Date.today(), Comments__c = '');
        insert ca;
        Callidus_Claim_Audit__c[] cca = [select claim_status__c  from Callidus_Claim_Audit__c where id = :ca.id];
        for(Callidus_Claim_Audit__c cc:cca)
        {
        	system.assertEquals('Filed', cc.claim_status__c);
        }
        
        Callidus_Claim_History__c chs = new Callidus_Claim_History__c(Claim__c = c.id, Comments__c = '', Action_Date__c = Date.today(), Claim_Status__c = 'Filed', User__c = UserInfo.getUserId());
        insert chs;
        Callidus_Claim_History__c[] chsList = [select Claim_Status__c from Callidus_Claim_History__c where id = :chs.id];
        for(Callidus_Claim_History__c cch:chsList)
        {
        	system.assertEquals('Filed', cch.Claim_Status__c);
        }
        try
        {
            Approval.ProcessSubmitRequest request =new Approval.ProcessSubmitRequest();
            request.setObjectId(c.Id);
            Approval.ProcessResult result = Approval.process(request);
        }
        catch(Exception e){}
        try
        {       
            system.assertEquals(null, ce.approve());
        }catch(Exception e){}
        try
        {       
//            system.assertEquals(null, ce.reject());
        }catch(Exception e){}
        
        ClaimHistories ch = new ClaimHistories('Test', 'Pending Approval', 'Admin', UserInfo.getUserId(), Date.today());
        ce.claimHistoryList = new List<ClaimHistories>();
        ce.claimHistoryList.add(ch);
        system.assertEquals('Admin', ce.claimHistoryList.get(0).userName);
        
        ce.getClaimHistories();
        system.assertEquals('success', ce.getClaimHistories());
        
        ce.changeCC();
        
        system.assertEquals(null, ce.fileClaim());
        system.assertEquals(null, ce.lookupPlanDocument());
        Test.stopTest(); 
    }
}